import { useMutation } from "@tanstack/react-query";
import { useErrorHandler } from "@/lib/error-handler";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import type { ErrorResponse, Response, ServiceValidateResponseData } from "@/types/response";
import { serviceValidateAPI } from "@/api";
import type { AxiosError } from "axios";

type ServiceValidateResponse = Response & { data: ServiceValidateResponseData };

/**
 * ServiceValidate hooks
 */
export const useServiceValidate = () => {
  const { t } = useTranslation();
  const errorHandler = useErrorHandler();

  // ServiceValidate mutation
  const serviceValidateMutation = useMutation({
    mutationFn: serviceValidateAPI.serviceValidate,
    onSuccess: (response: ServiceValidateResponse) => {
      if (response.code === 200) {
        toast.success(t("Service validate obtained successfully"), {
          description:
            response.message || t("Service validate has been obtained successfully."),
          duration: 5000,
        });
      } else {
        toast.error(t("Failed to service validate"), {
          description:
            response.message || t("Failed to service validate. Please try again."),
          duration: 5000,
        });
      }
    },
    onError: (error: AxiosError<ErrorResponse, unknown>) => {
      // 使用错误处理器获取错误信息
      const errorResult = errorHandler.handleApiError(error);

      // 根据错误类型显示不同颜色的弹窗
      if (errorResult.type === "warning") {
        toast.warning(t("Failed to service validate"), {
          description: errorResult.message,
          duration: 5000,
        });
      } else {
        toast.error(t("Failed to service validate"), {
          description: errorResult.message,
          duration: 5000,
        });
      }
      console.error("ServiceValidate error:", error);
    },
  });

  return {
    getServiceValidate: serviceValidateMutation.mutate,
    getServiceValidateAsync: serviceValidateMutation.mutateAsync,
    isPending: serviceValidateMutation.isPending,
    error: serviceValidateMutation.error,
    data: serviceValidateMutation.data,
  };
};
